<script setup>
import { cloneDeep } from 'lodash'
import {
  CustomizeOptionsList,
  ruleList
} from './options/options.js'

import FormInput from '../customizeOption/CustomizeFormInput.vue'
import FormSelect from '../customizeOption/CustomizeFormSelect.vue'
import showWordLimit from '../customizeOption/showWordLimit.vue'
import FormTextarea from '../customizeOption/FormTextarea.vue'
import FormCheckbox from '../customizeOption/CustomzieCheckBox.vue'

const props = defineProps({
  info: {
    type: Object,
    default: {}
  }
})
const emit = defineEmits(['saveOptions', 'cancelOptions'])
const customizeComponent = shallowRef({ FormInput, FormSelect, showWordLimit, FormTextarea, FormCheckbox })
// 表单
const CustomizeForm = ref(null)
//定制组件表单
const CustomizeOptionsForm = ref({})
//是否有内容
const hasInfo = computed(() => {
  return props.info.name
})

//定制组件表单校验规则
const CustomizeOptionsRule = computed(() => {

  if (props.info.name === 'CustomSelect' && CustomizeOptionsForm.value?.type === 'customize') {
    return {
      ...cloneDeep(ruleList[props.info.name]),
      optionsInfo: [{ required: true, message: '请输入自定义选项内容!', trigger: 'blur' }]
    }
  } else {

    return cloneDeep(ruleList[props.info.name])
  }
}
)


//组件配置项
const CustomizeOptions = ref([])

//组件内容自我依赖项
const optionSelfReliance = () => {

  CustomizeOptions.value = CustomizeOptions.value.map(item => {
    //单选 多选
    if (props.info.name === 'CustomCheckbox' || props.info.name === 'CustomRadio') {
      const name = props.info.name === 'CustomCheckbox' ? '多选框数量' : '单选框数量'
      if (item.name === '多选框名称' || item.name === '单选框名称') {
        item.$attrs.size = CustomizeOptions.value.find(item => item.name === name).value
        item.component = customizeComponent.value['FormInput']
      }
    }
    //时间选择器,选择器  
    else if (props.info.name === 'CustomDatePicker' || props.info.name === 'CustomSelect') {
      if (item.nameEn === 'type') {
        item.component = customizeComponent.value['FormSelect']
      } else if (item.nameEn === 'optionsInfo') {
        item.component = customizeComponent.value['FormTextarea']
      }
    }
    //输入框
    else if (props.info.name === 'CustomInput') {
      if (item.name === '类型') {
        item.component = customizeComponent.value['FormSelect']
      } else if (item.name === '是否长度限制') {
        item.component = customizeComponent.value['showWordLimit']
      }
    }
    //文件上传
    else if (props.info.name === 'CustomFile') {
      if (item.nameEn === 'fileType') {
        item.component = customizeComponent.value['FormCheckbox']
      }
    }

    return item
  })
  CustomizeOptionsForm.value = {}


}


//监听传入的info 看是否变化
watch(() => props.info, (val, o) => {
  if (!val) return
  console.log('%c [  ]-96', 'font-size:13px; background:pink; color:#bf2c9f;', val)
  // 每次变化则清空 form数据表单
  if (Object.keys(val).length) {
    // 连续两次点编辑的时候 表单变化 需要清除校验
    if (o && Object.keys(o).length) {
      CustomizeForm.value.resetFields()
    }

    if (props.info.option.length) {
      CustomizeOptions.value = cloneDeep(props.info.option)
    } else {
      CustomizeOptions.value = cloneDeep(CustomizeOptionsList[props.info.name])
    }

    console.log('%c [  ]-127', 'font-size:13px; background:pink; color:#bf2c9f;', CustomizeOptions.value)
    optionSelfReliance()
  }
},
  {
    immediate: true
  })


//监听配置内容 去更改form表单内容
watch(CustomizeOptions, () => {
  generateForm()
},
  {
    deep: true
  })



//监听表单内容
watch(CustomizeOptionsForm, (newVal, oldVal) => {

  if (props.info.name === 'CustomInput') {
    //是文本或文本域 则可用,否则禁用
    const type = CustomizeOptions.value.find(item => item.nameEn === 'type')
    // 是否文本或文本域
    const isText = type.value === 'text' || type.value === 'textarea'
    CustomizeOptions.value.forEach(item => {
      if (item.nameEn === 'LengthLimit') {
        item.$attrs.disabled = !isText
        if (!isText) {
          item.value.isShowLengthLimit = 'false'
        }
      } else if (item.nameEn === 'isShowLength' && !isText) {
        item.value = false
      }
    })

    if (isText) {
      //是否限制长度
      const isShowLengthExit = CustomizeOptions.value.includes(CustomizeOptions.value.find(item => item.nameEn === 'isShowLength'))
      const isShowLength = CustomizeOptionsForm.value.LengthLimit?.isShowLengthLimit === 'true'
      if (isText && isShowLength && !isShowLengthExit) {
        const item = {
          name: '是否展示长度',
          nameEn: 'isShowLength',
          value: false,
          component: 'el-switch',
          $attrs: {
            size: 'large',
            'inline-prompt': true,
            'active-text': '是',
            'inactive-text': '否'
          }
        }
        CustomizeOptions.value = CustomizeOptions.value.toSpliced(4, 0, item)
      } else if (!isText || (!isShowLength && isShowLengthExit)) {
        CustomizeOptions.value = CustomizeOptions.value.filter(item => item.nameEn !== 'isShowLength')
      }
    } else {

      CustomizeOptions.value = CustomizeOptions.value.filter(item => item.nameEn !== 'isShowLength')

    }

  } else if (props.info.name === 'CustomSelect') {

    //选择器类型
    const type = CustomizeOptionsForm.value.type
    const optionsInfo = Object.hasOwn(CustomizeOptionsForm.value, 'optionsInfo')

    if (type === 'customize' && !optionsInfo) {
      console.log('%c [  ]-180', 'font-size:13px; background:pink; color:#bf2c9f;', optionsInfo)

      const item =
      {
        name: '选项内容',
        nameEn: 'optionsInfo',
        value: '',
        component: customizeComponent.value['FormTextarea'],
        required: true,
        $attrs: {}
      }
      CustomizeOptions.value = CustomizeOptions.value.toSpliced(3, 0, item)

    } else if (type !== 'customize' && optionsInfo) {
      console.log('%c [  ]-180', 'font-size:13px; background:pink; color:#bf2c9f;', optionsInfo)

      CustomizeOptions.value = CustomizeOptions.value.filter(item => item.nameEn !== 'optionsInfo')
    }

  }

  // 动态绑定$attrs
  CustomizeOptions.value.forEach(item => {
    if (props.info.name === 'CustomCheckbox' && item.name === '多选框名称') {
      item.$attrs.size = CustomizeOptionsForm.value.size
    } else if (props.info.name === 'CustomRadio' && item.name === '单选框名称') {
      item.$attrs.size = CustomizeOptionsForm.value.size
    }
  })

},
  {
    deep: true
  })


//保存定制组件
const saveOptions = () => {
  CustomizeForm.value.validate((valid, fields) => {

    if (valid) {
      emit('saveOptions', props.info, CustomizeOptions.value)
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 重置
const resetOptions = () => {
  CustomizeForm.value.resetFields()
  CustomizeOptions.value = cloneDeep(CustomizeOptionsList[props.info.name])
  generateForm()
  optionSelfReliance()


}

//取消保存
const cancelOptions = () => {
  emit('cancelOptions', props.info)

  console.log('%c [  ]-106', 'font-size:13px; background:pink; color:#bf2c9f;', CustomizeOptions.value)
}

//生成表单数据
const generateForm = () => {
  Object.keys(CustomizeOptions.value) &&
    CustomizeOptions.value.forEach(item => {
      CustomizeOptionsForm.value[item.nameEn] = item.value
    })
}
</script>

<template>

  <div class="form-container">
    <el-card>
      <el-form v-if="hasInfo" ref="CustomizeForm" :model="CustomizeOptionsForm" :rules="CustomizeOptionsRule">
        <el-form-item v-for="item in CustomizeOptions" :prop=item.nameEn :label="item.name" label-width="100px">
          <component :is="item.component" v-model="item.value" v-bind="item.$attrs"></component>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="btn-group">
          <el-button class="btn" @click="saveOptions">保存设置</el-button>
          <el-button class="btn" @click="resetOptions">重置</el-button>
          <el-button @click="cancelOptions">取消</el-button>
        </div>
      </template>
    </el-card>
  </div>

</template>



<style lang="scss" scoped>
.form-container {
  height: 100%;

  .btn-group {
    display: flex;
    flex: 1;
    justify-content: center;
    gap: 20px;

    .btn {
      background: #040a77cf;
      color: #d8d8d8;
      transition: all 0.3s;

      &:hover {
        background: #999cdfb5;
        color: #4f4f4f;

      }
    }
  }



  :deep(.el-card) {
    height: 100%;
    display: flex;
    flex-direction: column;

    .el-card__body {
      flex: 1;
    }
  }
}
</style>